//
//  ViewController.m
//  GCD常用函数
//
//  Created by 李煜 on 2024/3/20.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic,strong) UIImage  *image1;
@property (nonatomic,strong) UIImage  *image2;

@end

@implementation ViewController


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

  [self mergeTwoPics];
}

//合并两张图片
- (UIImage *)drawPic {
  //开启上下文
  UIGraphicsBeginImageContext(CGSizeMake(200, 200));
  [self.image1 drawInRect:CGRectMake(0, 0, 200, 100)];
  [self.image2 drawInRect:CGRectMake(0, 100, 200, 100)];

  //获取图片
  UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();

  //   关闭上下文
  UIGraphicsEndImageContext();
  return finalImage;
}
- (void)mergeTwoPics {


  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

  dispatch_group_t group = dispatch_group_create();
  //下载图片1
  dispatch_group_async(group, queue, ^{
    NSString *urlStr1 = @"https://t7.baidu.com/it/u=2529476510,3041785782&fm=193&f=GIF";
    NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr1]];
    self.image1 = [UIImage imageWithData:data1];


  });
  //下载图片2
  dispatch_group_async(group, queue, ^{
    NSString *urlStr2 = @"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF";
    NSData *data2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr2]];
    self.image2 = [UIImage imageWithData:data2];
  });

  //等待图片1图片2下载完成,合并图片

  dispatch_group_notify(group, queue, ^{
    UIImage *finalImage = [self drawPic];
    dispatch_sync(dispatch_get_main_queue(), ^{
      self.imageView.image = finalImage;
    });
  });
}



@end
